const { USER_REGISTER, USER_LOGIN, USER_INFO } = require('./consts')
const { SuccessModel, ErrorModel } = require('../model/result')
const { handleUserRegister, handleUserLogin } = require('../controller/user')
const { setRedis } = require('../db/redis')
const { authFail } = require('../config/error/user')

// 处理用户相关路由
const userRouter = async (req, res) => {
  const { method, path } = req
  switch (method) {
    case 'get':
      // 用户信息获取
      if (path === USER_INFO) {
        // 无权限
        if (!req.session) {
          return new ErrorModel(authFail)
        }
        return new SuccessModel({
          message: '用户信息获取',
          data: {
            username: 'chigga',
            age: 18
          }
        })
      }
      break
    case 'post':
      if (path === USER_REGISTER) {
        // 用户注册
        return await handleUserRegister(req.body)
      } else if (path === USER_LOGIN) {
        // 用户登录
        const result = await handleUserLogin(req.body)
        // 保存登录状态
        if (result.code === 200) {
          const { username, password, gender } = result.data
          req.session.username = username
          req.session.password = password
          req.session.gender = gender
          // 同步到Redis中
          await setRedis(req.userId, req.session)
        }
        return result
      }
      break
    default:
      return new ErrorModel({
        message: '请求方式错误'
      })
  }
}

module.exports = userRouter
